<template>
  <div class="order-detail-container">
    <!-- 头部信息 -->
    <div class="header">
      <el-button type="text" @click="goBack" class="back-button">
        <el-icon><arrow-left /></el-icon> 返回
      </el-button>
      <h1 class="title">订单详情</h1>
      <div class="status-tag">
        <el-tag :type="getStatusTagType(order.status)" size="large">
          {{ getStatusLabel(order.status) }}
        </el-tag>
      </div>
    </div>

    <!-- 订单卡片容器（横向排列） -->
    <div class="cards-container">
      <!-- 订单基本信息 -->
      <el-card class="order-card">
        <div class="order-info">
          <div class="info-row">
            <span class="label">订单编号：</span>
            <span class="value">{{ order.order_no || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDateTime(order.created_at) }}</span>
          </div>
          <div class="info-row">
            <span class="label">租客ID：</span>
            <span class="value">{{ order.tenant_id || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="label">房东ID：</span>
            <span class="value">{{ order.landlord_id || '-' }}</span>
          </div>
        </div>
      </el-card>

      <!-- 租赁信息 -->
      <el-card class="order-card">
        <h3 slot="header">租赁信息</h3>
        <div class="rental-info">
          <div class="info-row">
            <span class="label">房源ID：</span>
            <span class="value">{{ order.house_id || '-' }}</span>
          </div>
          <div class="info-row">
            <span class="label">租赁周期：</span>
            <span class="value">
              {{ formatDate(order.start_date) }} 至 {{ formatDate(order.end_date) }}
              (共 {{ calculateDays(order.start_date, order.end_date) }} 天)
            </span>
          </div>
          <div class="info-row">
            <span class="label">总金额：</span>
            <span class="value amount">{{ order.total_amount || '0' }} 元</span>
          </div>
          <div class="info-row">
            <span class="label">押金：</span>
            <span class="value">{{ order.deposit || '0' }} 元</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button
          type="primary"
          v-if="order.status === 'pending'"
          @click="handlePay"
          size="large"
      >
        立即支付
      </el-button>
      <el-button
          type="danger"
          v-if="order.status === 'pending'"
          @click="handleCancel"
          size="large"
      >
        取消订单
      </el-button>
      <el-button
          type="success"
          v-if="order.status === 'paid'"
          @click="handleConfirm"
          size="large"
      >
        确认入住
      </el-button>
    </div>

    <!-- 支付对话框 -->
    <el-dialog v-model="showPayDialog" title="订单支付" width="30%">
      <div class="payment-info">
        <p>订单编号：{{ order.order_no }}</p>
        <p>支付金额：<span class="amount">{{ order.total_amount + order.deposit }} 元</span></p>
      </div>
      <div class="payment-methods">
        <el-radio-group v-model="paymentMethod">
          <el-radio label="wechat">
            <el-icon><picture /></el-icon> 微信支付
          </el-radio>
          <el-radio label="alipay">
            <el-icon><picture /></el-icon> 支付宝
          </el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <el-button @click="showPayDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmPay">确认支付</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeft, Picture } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import common_util from "../../util/common_util.js";

const route = useRoute()
const router = useRouter()
const orderId = ref(route.params.orderId)

console.log("orderId-------------"+orderId.value)

// 订单状态映射
const statusMap = {
  pending: { label: '待支付', type: 'warning' },
  paid: { label: '已支付', type: 'success' },
  canceled: { label: '已取消', type: 'info' },
  completed: { label: '已完成', type: '' }
}

// 订单数据
const order = ref({
  order_id: '',
  order_no: '',
  status: 'pending',
  tenant_id: '',
  landlord_id: '',
  house_id: '',
  start_date: '',
  end_date: '',
  total_amount: 0,
  deposit: 0,
  created_at: ''
})

// 支付相关
const showPayDialog = ref(false)
const paymentMethod = ref('wechat')

// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    const response = await axios.get(`/api/orders/${orderId.value}`, {
      headers: common_util.accessHeader()
    })
    console.log("Current user ID (from token):", response.config.headers.Authorization)
    console.log("Order data:", response.data.data)

    if (response.data.code === 0) {
      order.value = response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取订单详情失败')
      router.push({ name: 'order-list' })
    }
  } catch (error) {
    if (error.response?.status === 403) {
      ElMessage.error('无权查看此订单')
    } else {
      ElMessage.error('获取订单详情失败')
    }
    console.error(error)
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString()
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 计算租赁天数
const calculateDays = (startDate, endDate) => {
  if (!startDate || !endDate) return 0
  const start = new Date(startDate)
  const end = new Date(endDate)
  const diffTime = Math.abs(end - start)
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

// 获取状态标签
const getStatusLabel = (status) => {
  return statusMap[status]?.label || status
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  return statusMap[status]?.type || ''
}

// 支付操作
const handlePay = () => {
  showPayDialog.value = true
}

// 确认支付
const confirmPay = async () => {
  try {
    // 模拟支付成功逻辑（无需调用后端）
    ElMessage.success('支付成功')
    showPayDialog.value = false // 关闭支付对话框
    await fetchOrderDetail() // 刷新订单详情（如需）
  } catch (error) {
    ElMessage.error('支付失败')
    console.error(error)
  }
}
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消此订单吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.put(
          `/api/orders/${orderId.value}`,
          { status: 'canceled' }, // 请求体：明确传递要更新的状态
          { headers: common_util.accessHeader() } // 正确传递 headers
      );
      if (response.data.code === 0) {
        ElMessage.success('订单已取消');
        await fetchOrderDetail();
      } else {
        ElMessage.error(response.data.msg || '取消订单失败');
      }
    } catch (error) {
      ElMessage.error('取消订单失败');
      console.error(error);
    }
  }).catch(() => {});
};

// 确认入住
const handleConfirm = () => {
  ElMessageBox.confirm('确认已完成入住?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.post(`/api/orders/${orderId.value}/complete`)
      if (response.data.code === 0) {
        ElMessage.success('操作成功')
        await fetchOrderDetail()
      } else {
        ElMessage.error(response.data.msg || '操作失败')
      }
    } catch (error) {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }).catch(() => {})
}

// 返回
const goBack = () => {
  router.go(-1)
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped>
.order-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 卡片横向排列容器 */
.cards-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

/* 卡片样式 */
.order-card {
  flex: 1;
  min-width: 0;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.back-button {
  padding: 10px 0;
}

.title {
  font-size: 24px;
  margin: 0;
  flex-grow: 1;
}

.status-tag .el-tag {
  font-size: 14px;
  padding: 0 12px;
  height: 28px;
  line-height: 28px;
}

.info-row {
  display: flex;
  margin-bottom: 12px;
  line-height: 1.6;
}

.label {
  width: 100px;
  color: #666;
  font-weight: bold;
}

.value {
  flex: 1;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}

.payment-info {
  margin-bottom: 20px;
  line-height: 1.8;
}

.payment-methods {
  margin-top: 20px;
}

.payment-methods .el-radio {
  display: block;
  margin-bottom: 15px;
}

.payment-methods .el-icon {
  margin-right: 8px;
  font-size: 20px;
  vertical-align: middle;
}

/* 响应式设计 - 小屏幕下改为纵向排列 */
@media (max-width: 768px) {
  .cards-container {
    flex-direction: column;
  }
}
</style>